<template>
  <el-drawer
    v-model="showDrawer"
    :title="drawerTitle"
    size="30%"
    @close="close"
  >
    <el-form
      ref="payPwdFormRef"
      :model="payPwdForm"
      :rules="rules"
      label-position="top"
    >
      <el-form-item
        v-if="opt === 'modify'"
        prop="currentPwd"
        :label="$t('当前密码')"
      >
        <el-input
          v-model="payPwdForm.currentPwd"
          :placeholder="$t('请输入当前密码')"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('新的交易密码')" prop="password">
        <el-input
          v-model="payPwdForm.password"
          :placeholder="$t('请设置新密码')"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('确认密码')" prop="confirmPwd">
        <el-input
          v-model="payPwdForm.confirmPwd"
          :placeholder="$t('请再次输入新密码')"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <!-- <el-form-item prop="code">
          <div class="codeRow">
            <el-input
              style="width: 80%"
              v-model="payPwdForm.code"
              :placeholder="$t('请输入验证码')"
              type="number"
            ></el-input>
            <el-button
              :loading="loading"
              type="primary"
              @click="getVerificationCode"
              :disabled="sec !== 60"
            >
              {{ sec === 60 ? "获取验证码" : `${sec}s` }}
            </el-button>
          </div>
        </el-form-item> -->

      <el-form-item>
        <el-button
          style="width: 100%"
          size="large"
          type="primary"
          @click="submitForm(payPwdFormRef)"
        >
          {{ $t("确认") }}
        </el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script setup>
import { ref, reactive, watch, toRefs, computed } from "vue";
import { emailSendApi, setPayPasswordNewApi } from "@/api/login/index";
import { useI18n } from "vue-i18n";
import _ from "lodash";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  codeType: {
    type: String,
    default: "modify",
  },
  drawerTitle: {
    type: String,
    default: "设置交易密码",
  },
});
const emit = defineEmits(["close"]);

const loading = ref(false);
const opt = ref(props.codeType);
const sec = ref(60);
const timer = ref(null);
const showDrawer = ref(false);
watch(
  () => props.show,
  (newVal) => {
    showDrawer.value = newVal;
    console.log(showDrawer, props);
  }
);
const payPwdFormRef = ref();
const payPwdForm = reactive({
  password: "",
  confirmPwd: "",
  currentPwd: "",
  // code: "",
});

const checkPwd = (rule, value, callback) => {
  if (!value) {
    callback(new Error(t("请设置新密码")));
  } else {
    const checkPwdFormat = new RegExp(/^[0-9a-zA-Z]{6,16}$/);
    if (!checkPwdFormat.test(value)) {
      callback(new Error(t("密码最少6位，可使用字母和数字")));
      return;
    }
    callback();
  }
};
const checkConFirmPwd = (rule, value, callback) => {
  if (!value) {
    callback(new Error(t("请再次输入新密码")));
  } else if (value !== payPwdForm.password) {
    callback(new Error(t("密码不一致,请重新输入")));
  } else {
    callback();
  }
};

const rules = computed(() => {
  return {
    currentPwd: [
      { required: true, message: t("请输入当前密码"), trigger: "blur" },
    ],
    password: [{ required: true, validator: checkPwd, trigger: "blur" }],
    confirmPwd: [
      { required: true, validator: checkConFirmPwd, trigger: "blur" },
    ],
    // code: [{ required: true, message: t("请输入验证码"), trigger: "blur" }],
  };
});

// 倒计时
const timerHandle = () => {
  clearInterval(timer);
  timer.value = setInterval(() => {
    if (sec.value > 0) {
      sec.value--;
    } else {
      sec.value = 60;
    }
  }, 1000);
};

const getVerificationCode = async () => {
  try {
    loading.value = true;
    const res = await emailSendApi({
      code_type: "set_trade_password",
    });
    if (res) {
      timerHandle();
    }
    loading.value = false;
  } catch (e) {
    loading.value = false;
    return false;
  }
};

const form = computed(() => {
  let res = {
    password: payPwdForm.password,
    confirm_password: payPwdForm.confirmPwd,
    // code: payPwdForm.code,
    opt: opt.value,
  };

  if (opt.value === "modify") {
    res.current_password = payPwdForm.currentPwd;
  }

  return res;
});

const close = () => {
  if (payPwdFormRef.value) {
    payPwdFormRef.value.resetFields();
  }
  emit("close");
};

// 验证表单，验证通过后请求设置支付密码接口
const submitForm = (formRef) => {
  console.log(formRef);
  if (!formRef) return;
  formRef.validate(async (valid, fields) => {
    if (valid) {
      console.log("submit!");
      const res = await setPayPasswordNewApi(form.value);
      if (res) {
        emit("close");
        payPwdForm.password = "";
        ElMessage({
          showClose: false,
          message: t("设置成功！"),
          type: "success",
          grouping: true,
        });

        for (const item in payPwdForm) {
          payPwdForm[item] = "";
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>
<style lang="scss">
.codeRow {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
